#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    createActions();
    initSysTray();

    myOptionsDialog = new optionsDialog( this );

    progress = new myProgressDialog( 0, Qt::WindowTitleHint | Qt::WindowSystemMenuHint );
    connect( progress, SIGNAL( cancelCalled() ), this, SLOT( on_cancelThread_clicked() ) );

    connect( &cleanupTread, SIGNAL( finished() ), this, SLOT( threadFinished() ) );
    connect( &cleanupTread, SIGNAL( makeStep( double ) ), this, SLOT( processStep( double ) ) );

    QRect frect = frameGeometry();
    frect.moveCenter(QDesktopWidget().availableGeometry().center());
    move(frect.topLeft());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::on_actionOptions_triggered()
{
    if ( !myOptionsDialog->isHidden() )
        myOptionsDialog->show();
    else
        myOptionsDialog->run_form();
}

void MainWindow::createActions()
{
    showAction = new QAction(tr("&Show"), this);
    connect(showAction, SIGNAL(triggered()), this, SLOT(showNormal()));

    connect(ui->actionClose_to_tray, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionShutdown, SIGNAL(triggered()), qApp, SLOT(quit()));

    connect(ui->actionCleanup_USB_Drive, SIGNAL(triggered()), this, SLOT(on_driveCleanupButton_clicked()));
    connect(ui->actionCleanup_All_USB_Drives, SIGNAL(triggered()), this, SLOT(on_allDrivesCleanupButton_clicked()));
    connect(ui->actionCustom_Cleanup, SIGNAL(triggered()), this, SLOT(on_folderCleanupButton_clicked()));
}

void MainWindow::initSysTray()
{
    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction( showAction );
    trayIconMenu->addAction( ui->actionOptions );
    trayIconMenu->addSeparator();
    trayIconMenu->addAction( ui->actionCleanup_USB_Drive );
    trayIconMenu->addAction( ui->actionCleanup_All_USB_Drives );
    trayIconMenu->addAction( ui->actionCustom_Cleanup );
    trayIconMenu->addSeparator();
    trayIconMenu->addAction( ui->actionClose_to_tray );
    trayIconMenu->addAction( ui->actionShutdown );

    trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon( QIcon(":/images/open.png") );
    trayIcon->setContextMenu(trayIconMenu);
    trayIcon->show();

    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
            this, SLOT( iconActivated(QSystemTrayIcon::ActivationReason) ));
}

void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::DoubleClick )
        this->showNormal();
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (trayIcon->isVisible())
    {
        hide();
        event->ignore();
    }
}

void MainWindow::setLastSourceFolder( const QString &path )
{
    QSettings settings("Affinity-Tools", "USBDriveFresher");
    settings.setValue("LastCleanupFolder", path );
}

QString MainWindow::getLastSourceFolder() const
{
    QSettings settings("Affinity-Tools", "USBDriveFresher");
    return settings.value("LastCleanupFolder", "" ).toString();
}

void MainWindow::on_driveCleanupButton_clicked()
{
    myCleanUSBDialog clDlg(this);
    if ( clDlg.run_form() )
    {
        QStringList inList;
        genDrivesList.clear();
        genDrivesList = clDlg.getDataList();
        for (int i = 0; i < genDrivesList.size(); i++)
            inList.append( genDrivesList.at(i).driveLetter );

        cleanupTread.setRunMode( 1, inList );
        startCleanup();
    }
}

void MainWindow::on_allDrivesCleanupButton_clicked()
{
    switch( QMessageBox::warning( this, "USB Drive Refresher",
                                  "Are you sure you want to cleanup all USB drives connected?",
                                  "Yes",
                                  "No", 0, 0, 1 ) )
    {
    case 1:
        {
            return;
        }
    }

    myCleanUSBDialog clDlg(this);
    QStringList inList;
    genDrivesList.clear();
    genDrivesList = clDlg.getAllDataList();
    for (int i = 0; i < genDrivesList.size(); i++)
        inList.append( genDrivesList.at(i).driveLetter );

    cleanupTread.setRunMode( 1, inList );
    startCleanup();
}

void MainWindow::on_folderCleanupButton_clicked()
{
    QString dirPath = QFileDialog::getExistingDirectory ( this,
                                                          "Select folder to cleanup",
                                                          getLastSourceFolder() );
    if ( !dirPath.isEmpty() )
    {
        genDrivesList.clear();
        setLastSourceFolder( dirPath );

        drivesData myFolderData;
        myFolderData.driveLetter = dirPath;
        myFolderData.driveSerial = "";
        myFolderData.driveFreeSize = 0;
        myFolderData.driveLabel = dirPath;
        genDrivesList.append(myFolderData);

        cleanupTread.setRunMode( 2, QStringList(dirPath) );
        startCleanup();
    }
}

void MainWindow::deviceArrived( const QString &disk, int flags )
{
    if ( mySettings::autoCleanup() )
    {
        genDrivesList.clear();
        cleanupTread.setRunMode( 0, QStringList(disk) );
        startCleanup();
    }
}

void MainWindow::on_cancelThread_clicked()
{
    if ( cleanupTread.isRunning() )
    {
        cleanupTread.terminate();
        cleanupTread.wait();
    }
}

void MainWindow::startCleanup()
{
    if ( !mySettings::silentAutoCleanup() )
    {
        progress->reset();
        progress->show();
    }
    cleanupTread.start();
}

void MainWindow::threadFinished()
{
    if ( !progress->isHidden() )
        progress->setValue( progress->maximum() );

    QString usbText = tableText;
    QList<cleanDataStruct*> tempList = cleanupTread.getCleanupList();
    if ( tempList.size() > 0 )
    {
        for ( int i = 0; i < tempList.size(); i++ )
        {
            unsigned long freeSpaceAfter = 0;
            if ( genDrivesList.at(i).driveFreeSize != 0 )
                freeSpaceAfter = genDrivesList.at(i).driveFreeSize - tempList.at(i)->cleanedSize;
            usbText.replace( "text1", tempList.at(i)->cleanPath );
            usbText.replace( "text2", genDrivesList.at(i).driveLabel );
            usbText.replace( "fs1", QString::number( genDrivesList.at(i).driveFreeSize ) + " b"  );
            usbText.replace( "fs2", QString::number( freeSpaceAfter ) + " b" );
            usbText.replace( "fs3", QString::number( tempList.at(i)->cleanedSize ) + " b" );
            usbText.replace( "fs4", QString::number( tempList.at(i)->deletedItems) );
        }
        QString endLine = "</body> </html>";
        statisticsDialog stat(this);
        stat.setStatisticsData( htmlText + usbText + endLine );
        stat.exec();
    }
}

void MainWindow::processStep( double factor )
{
    if ( !progress->isHidden() )
    {
        int absValue = factor*100;
        progress->setValue( absValue );
    }
}
